<?php


namespace app\shop\controller\admin;


use app\shop\controller\BaseAdminController;
use app\shop\model\order\OrderComplainModel;
use app\shop\model\order\OrderModel;
use app\shop\model\user\UserModel;
use think\App;
use think\facade\Db;
use think\Request;

class ComplainController extends BaseAdminController
{
    public function __construct(App $app)
    {
        $this->model = new OrderComplainModel();
        $this->search = $this->setSearch($app->request);
        parent::__construct($app);
    }

    function setSearch(Request $request)
    {
        $where = [];
        $designName = $request->param('design_name', '', 'trim');
        if ($designName) {
            $designId = UserModel::where('realname', $designName)->value('user_id');
            $where[] = ['design_id', '=', $designId];
        }
        return [
            'like' => ['order_sn'],
            '=' => ['status'],
            'custom' => $where,
        ];
    }

    public function getList()
    {
        try {
            $list = parent::getList()->each(function ($item) {
                $item['status_txt'] = $item['status'] == 0 ? '待处理' : '已处理';
                $item['design_name'] = UserModel::where('user_id', $item['design_id'])->value('realname', '');
                $item['user_mobile'] = UserModel::where('user_id', $item['user_id'])->value('mobile', '');
                return $item;
            });
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


    public function save(array $data = [])
    {
        Db::startTrans();
        try {
            $data = $this->request->param('', '', 'trim');
            $data['status'] = 1;

            $orderSn = $this->model->where('id', $data['id'])->value('order_sn');

            $orderInfo = OrderModel::where('order_sn', $orderSn)->find();
            if ($orderInfo) {
                $orderInfo->is_complaint = 2;
                $orderInfo->save();
            }


            parent::save($data);

            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }
}